package com.itheima.service.mongo.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import com.itheima.domain.mongo.RecommendVideo;
import com.itheima.domain.mongo.Video;
import com.itheima.domain.vo.PageBeanVo;
import com.itheima.service.mongo.VideoService;
import com.itheima.util.ConstantUtil;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;


/**
 * @Author 请不要叫我高司令
 * @Date 2022/3/23 17:55
 * @Version 1.0
 */

@DubboService
public class VideoServiceImpl implements VideoService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private RedisIdService redisIdService;

    @Override
    public PageBeanVo findVideoByPage(Long userId, Integer pageNum, Integer pageSize) {

        Query query = new Query(
                Criteria.where("userId").is(userId)
        ).with(Sort.by(Sort.Order.desc("date"))).with(Sort.by(Sort.Order.desc("score")))
                .skip((pageNum - 1) * pageSize).limit(pageSize);

        //查询推荐视频id列表
        List<RecommendVideo> recommendVideoList = mongoTemplate.find(query, RecommendVideo.class);

        //查询视频详情
        ArrayList<Video> videoList = new ArrayList<>();

        if (CollectionUtil.isNotEmpty(recommendVideoList)) {
            for (RecommendVideo recommendVideo : recommendVideoList) {

                Video video = mongoTemplate.findById(recommendVideo.getVideoId(), Video.class);

                videoList.add(video);
            }
        }

        //返回并封装分页对象
        return new PageBeanVo(pageNum, pageSize, 0L, videoList);

    }

    @Override
    public void saveVideo(Video video) {


        //1.设置视频vid
        Long vid = redisIdService.getNextId(ConstantUtil.VIDEO_ID);
        video.setVid(vid);

        //2.保存
        mongoTemplate.save(video);

        //3.将自己的视频推荐给自己
        RecommendVideo recommendVideo = new RecommendVideo();
        recommendVideo.setDate(System.currentTimeMillis());
        recommendVideo.setVid(video.getVid());
        recommendVideo.setUserId(video.getUserId());
        recommendVideo.setVideoId(video.getId());
        recommendVideo.setScore(RandomUtil.randomDouble(60, 90));
        mongoTemplate.save(recommendVideo);


    }
}




